<?php
// +----------------------------------------------------------------------
// | 产品管理模型
// +----------------------------------------------------------------------

namespace User\Model;

use Common\Model\RelationModel;

class WorksModel extends RelationModel{


    //array(填充字段,填充内容,[填充条件,附加规则])
    protected $_auto	 =	 array(
        array('iftj', 0, self::MODEL_INSERT,'string'),
        array('ifindex', 0, self::MODEL_INSERT,'string'),
        array('status', 0, self::MODEL_INSERT,'string'),
        array('sort', '0', self::MODEL_INSERT,'string'),
        array('create_time','time',self::MODEL_INSERT,'function')
    );

    //关联属性是以当前模型为主
    protected $_link = array(
        //关联操作步骤
        'works_makestep'=>array(
            'mapping_type'      => self::HAS_MANY,
            'foreign_key'       => 'workid',
            'class_name'        => 'works_makestep',
            'mapping_fields'    => array('id','scontent','simage'),
            'mapping_order'     => 'id ASC'
            ),
        //关联材料
        'works_materials'=>array(
            'mapping_type'  => self::HAS_MANY,
            'foreign_key'   => 'workid',
            'class_name'    => 'works_materials',
            'mapping_fields'=>'id,mname,mvalue',
            'mapping_order' =>' id ASC'
            )
    );

    /**
     * 添加作品信息模型
     * @param $data 页面POST的数
     * @return boolean|error
     */
    public function addModel($data) {
        if (empty($data)) {
            $this->error = '添加数据不能为空！';
            return false;
        }
        //终极栏目设置
        if(empty($data['cateid'])){
            $this->error='栏目错误,请关闭本页再试';
            return false;
        }
        if(mb_strlen($data['title'],'utf-8')<1 || mb_strlen($data['title'],'utf-8')>30){
            $this->error='作品名称不能为空且不能超过30个字符';
            return false;
        }
        if(empty($data['image'])){
            $this->error='请上传作品主图';
            return false;
        }
        if(empty($data['content'])){
            $this->error='请添加作品说明';
            return false;
        }

        if(empty($data['mname'][0]) || empty($data['mvalue'][0])){
            $this->error='请至少填写一项作品用料';
            return false;
        }
        //yf start
        foreach($data['mname'] as $k => $v)
        {
        	if(empty($v) && empty($data['mvalue'][$k]))
        	{
        		unset($data['mname'][$k]);
        		unset($data['mvalue'][$k]);
        	}
        	elseif(empty($v) || empty($data['mvalue'][$k]))
        	{
        		$this->error='请补全作品用料名称或者是用量';
        		return false;
        	}
        }
        //yf end
        if(empty($data['simage'][0]) || empty($data['scontent'][0])){
            $this->error='请至少填写一项作品操作步骤';
            return false;
        }
        
        //yf start
        foreach($data['simage'] as $kk => $vv)
        {
        	if(empty($vv) && empty($data['scontent'][$kk]))
        	{
        		unset($data['simage'][$kk]);
        		unset($data['scontent'][$kk]);
        	}
        	elseif(empty($vv) || empty($data['scontent'][$kk]))
        	{
        		$this->error='请补全步骤图或者是步骤描述';
        		return false;
        	}
        }
        $data['status'] = 0;
		unset($data['files']);
        $mname=$data['mname'];
        $mvalue=$data['mvalue'];
        $simage=$data['simage'];
        $scontent=$data['scontent'];
        $result = $this->create($data, 1);
        if ($result) {
            //添加数据
            $workid = $this->add($result);
            if ($workid) {
                //更新附件状态
                if ($data['image']) {
                    //更新主图与附件关联表
                    service("Attachment")->api_update('', 'works-' . $workid, 1);
                }
                //更新材料
                if($mname){
                    $datas['workid']=$workid;
                    foreach($mname as $key=>$value){
                        //添加附件到产品附件表
                        $datas['mname']=$value;
                        $datas['mvalue']=$mvalue[$key];
                        M('works_materials')->data($datas)->add();
                    }
                }
                unset($datas);
                //更新步骤
                if($scontent){
                    $arr['workid']=$workid;
                    foreach($scontent as $key=>$value){
                        //添加附件到产品附件表
                        $arr['scontent']=$value;
                        $arr['simage']=$simage[$key];
                        M('works_makestep')->data($arr)->add();
                    }
                }
                return $workid;
            } else {
                $this->error = '产品添加失败';
                return false;
            }
        } else {
            return false;
        }
    }
    /**
     * 保存草稿作品
     * @param $data
     * @return
     */
    public function addtempModel($data) {
    	if (empty($data)) {
    		$this->error = '添加数据不能为空！';
    		return false;
    	}
    	//终极栏目设置
    	if(empty($data['cateid'])){
    		$this->error='栏目错误,请关闭本页再试';
    		return false;
    	}
    	if(mb_strlen($data['title'],'utf-8')<1 || mb_strlen($data['title'],'utf-8')>30){
    		$this->error='作品名称不能为空且不能超过30个字符';
    		return false;
    	}
    	if(empty($data['image'])){
    		$this->error='请上传作品主图';
    		return false;
    	}
    
    	//yf start
    	foreach($data['mname'] as $k => $v)
    	{
    		if(empty($v) && empty($data['mvalue'][$k]))
    		{
    			unset($data['mname'][$k]);
    			unset($data['mvalue'][$k]);
    		}
    	}
    	//yf end
    
    	//yf start
    	foreach($data['simage'] as $kk => $vv)
    	{
    		if(empty($vv) && empty($data['scontent'][$kk]))
    		{
    			unset($data['simage'][$kk]);
    			unset($data['scontent'][$kk]);
    		}
    	}
    	unset($data['files']);
    	$mname=$data['mname'];
    	$mvalue=$data['mvalue'];
    	$simage=$data['simage'];
    	$scontent=$data['scontent'];
    	$result = $this->create($data, 1);
        $result['status'] = 5;
     
    	if ($result) {
    		//添加数据
    		$workid = $this->add($result);
    		if ($workid) {
    			//更新附件状态
    			if ($data['image']) {
    				//更新主图与附件关联表
    				service("Attachment")->api_update('', 'works-' . $workid, 1);
    			}
    			//更新材料
    			if($mname){
    				$datas['workid']=$workid;
    				foreach($mname as $key=>$value){
    					//添加附件到产品附件表
    					$datas['mname']=$value;
    					$datas['mvalue']=$mvalue[$key];
    					M('works_materials')->data($datas)->add();
    				}
    			}
    			unset($datas);
    			//更新步骤
    			if($scontent){
    				$arr['workid']=$workid;
    				foreach($scontent as $key=>$value){
    					//添加附件到产品附件表
    					$arr['scontent']=$value;
    					$arr['simage']=$simage[$key];
    					M('works_makestep')->data($arr)->add();
    				}
    			}
    			return $workid;
    		} else {
    			$this->error = '产品添加失败';
    			return false;
    		}
    	} else {
    		return false;
    	}
    }


    /**
     * 更新作品模型
     * @param $post
     * @return bool
     */
    public function editModel($data){
        if(empty($data['workid'])){
            $this->error='获取产品失败';
            return false;
        }
        if(mb_strlen($data['title'],'utf-8')<1 || mb_strlen($data['title'],'utf-8')>30){
            $this->error='作品名称不能为空且不能超过30个字符';
            return false;
        }
        if(empty($data['image'])){
            $this->error='请上传产品主图';
            return false;
        }
        if(empty($data['mname'][0]) && empty($data['mvalue'][0])){
            $this->error='请至少填写一项作品用料';
            return false;
        }
        
        //yf start
        foreach($data['mname'] as $k => $v)
        {
        	if(empty($v) && empty($data['mvalue'][$k]))
        	{
        		unset($data['mname'][$k]);
        		unset($data['mvalue'][$k]);
        	}
        	elseif(empty($v) || empty($data['mvalue'][$k]))
        	{
        		$this->error='请补全作品用料名称或者是用量';
        		return false;
        	}
        }
        //yf end
    	if(empty($data['simage'][0]) && empty($data['scontent'][0])){
            $this->error='请至少填写一项作品操作步骤';
            return false;
        }
        
        //yf start
        foreach($data['simage'] as $kk => $vv)
        {
        	if(empty($vv) && empty($data['scontent'][$kk]))
        	{
        		unset($data['simage'][$kk]);
        		unset($data['scontent'][$kk]);
        	}
        	elseif(empty($vv) || empty($data['scontent'][$kk]))
        	{
        		$this->error='请补全步骤图或者是步骤描述';
        		return false;
        	}
        }
        unset($data['files']);
        $workid=$data['workid'];
        $mname=$data['mname'];
        $mvalue=$data['mvalue'];
        $mtid=$data['materials_id'];
        $simage=$data['simage'];
        $scontent=$data['scontent'];
        $stepid=$data['stepid'];
        $result = $this->create($data, 2);
        if ($result) {
            //修改数据
            $where['workid']=$workid;
            $status=$this->data($result)->where($where)->save();
            //更新记录,记得如果是TRUE就为===,如果为FLASH则为!==,并不是!=
            if(false!==$status){
                //更新动态状态
               // M('UserDynamic')->where(array('infoid'=>$workid,'userid'=>$data['userid'],'action'=>'workadd'))->setField(array('status'=>false));

                //更新附件状态
                if ($data['image'] || $data['simage']) {
                    //更新主图与附件关联表
                    service("Attachment")->api_update('', 'works-' . $workid, 1);
                }
                //更新材料
                if($mname){
                    $datas['workid']=$workid;
                    foreach($mname as $key=>$value){
                        $datas['mname']=$value;
                        $datas['mvalue']=$mvalue[$key];
                        $datas['id']=$mtid[$key];
                        if(!empty($datas['id'])){
                            M('works_materials')->data($datas)->save();
                        }else{
                            M('works_materials')->data($datas)->add();
                        }
                    }
                }
                unset($datas);
                //更新步骤
                if($scontent){
                    $arr['workid']=$workid;
                    M('works_makestep')->where(array('workid'=>$workid))->delete();
                    foreach($scontent as $k=>$v){
                        $arr['scontent']=$v;
                        $arr['simage']=$simage[$k];
                        $arr['id']=$stepid[$k];
                        if(!empty($arr['id'])){
                            M('works_makestep')->data($arr)->save();
                        }else{
                            M('works_makestep')->data($arr)->add();
                        }
                    }
                }
                return true;
            } else {
                $this->error = '产品更新失败';
                return false;
            }
        } else {
            return false;
        }

    }
    
    public function edittempModel($data){
    	if(empty($data['workid'])){
    		$this->error='获取产品失败';
    		return false;
    	}
    	if(mb_strlen($data['title'],'utf-8')<1 || mb_strlen($data['title'],'utf-8')>30){
    		$this->error='作品名称不能为空且不能超过30个字符';
    		return false;
    	}
    	if(empty($data['image'])){
    		$this->error='请上传产品主图';
    		return false;
    	}
    
    	//yf start
    	foreach($data['mname'] as $k => $v)
    	{
    		if(empty($v) && empty($data['mvalue'][$k]))
    		{
    			unset($data['mname'][$k]);
    			unset($data['mvalue'][$k]);
    		}
    	}
    	//yf end
    
    	//yf start
    	foreach($data['simage'] as $kk => $vv)
    	{
    		if(empty($vv) && empty($data['scontent'][$kk]))
    		{
    			unset($data['simage'][$kk]);
    			unset($data['scontent'][$kk]);
    		}
    	}
    	unset($data['files']);
    	$workid=$data['workid'];
    	$mname=$data['mname'];
    	$mvalue=$data['mvalue'];
    	$mtid=$data['materials_id'];
    	$simage=$data['simage'];
    	$scontent=$data['scontent'];
    	$stepid=$data['stepid'];
    	$result = $this->create($data, 2);
    	if ($result) {
    		//修改数据
    		$where['workid']=$workid;
    		$status=$this->data($result)->where($where)->save();
    		//更新记录,记得如果是TRUE就为===,如果为FLASH则为!==,并不是!=
    		if(false!==$status){
    			//更新动态状态
    			//M('UserDynamic')->where(array('infoid'=>$workid,'userid'=>$data['userid'],'action'=>'workadd'))->setField(array('status'=>false));
    
    			//更新附件状态
    			if ($data['image'] || $data['simage']) {
    				//更新主图与附件关联表
    				service("Attachment")->api_update('', 'works-' . $workid, 1);
    			}
    			//更新材料
    			if($mname){
    				$datas['workid']=$workid;
    				foreach($mname as $key=>$value){
    					$datas['mname']=$value;
    					$datas['mvalue']=$mvalue[$key];
    					$datas['id']=$mtid[$key];
    					if(!empty($datas['id'])){
    						M('works_materials')->data($datas)->save();
    					}else{
    						M('works_materials')->data($datas)->add();
    					}
    				}
    			}
    			unset($datas);
    			//更新步骤
    			if($scontent){
    				$arr['workid']=$workid;
    				M('works_makestep')->where(array('workid'=>$workid))->delete();
    				foreach($scontent as $k=>$v){
    					$arr['scontent']=$v;
    					$arr['simage']=$simage[$k];
    					$arr['id']=$stepid[$k];
    					if(!empty($arr['id'])){
    						M('works_makestep')->data($arr)->save();
    					}else{
    						M('works_makestep')->data($arr)->add();
    					}
    				}
    			}
    			return true;
    		} else {
    			$this->error = '产品更新失败';
    			return false;
    		}
    	} else {
    		return false;
    	}
    
    }

    /**
     * 删除产品
     * @param $data
     * @return bool
     */
    public function deleteModel($data){
        if(empty($data)){
            $this->error='产品删除失败';
            return false;
        }
        $where['workid']=$data;
        $status=$this->relation(true)->where($where)->delete();
        if($status!==false){
            //删除产品主图
            service("Attachment")->api_delete('works-' . $data);
            return true;
        }else{
            return false;
        }
    }

    /**
     * 删除操作步骤
     * @param $id
     * @return bool
     */
    public function deleteMakeStepModel($id){
        if(empty($id)){
            $this->error='信息删除请求失败';
            return false;
        }
        $where['id']=$id;
        $status=M('WorksMakestep')->where($where)->delete();
        if($status!==false){
            return true;
        }else{
            return false;
        }
    }


    //获取数据
    public function getCategoryData(){
        $data= M('Category')->field(array('cateid,parentid'))->order('sort DESC')->select();
        $CategoryIds = array();
        foreach ($data as $r) {
            $CategoryIds[$r['cateid']] = array(
                'cateid' => $r['cateid'],
                'parentid' => $r['parentid'],
            );
        }
        return $CategoryIds;
    }


    //随拍作品添加模型
    public function suipaiAddModel($data){
        if (empty($data)) {
            $this->error = '添加数据不能为空！';
            return false;
        }
        if(mb_strlen($data['title'],'utf-8')<1 || mb_strlen($data['title'],'utf-8')>30){
            $this->error='作品名称不能为空且不能超过30个字符';
            return false;
        }
        if(empty($data['image'])){
            $this->error='请上传作品主图';
            return false;
        }
        if(empty($data['content'])){
            $this->error='请添加作品说明';
            return false;
        }
        $data['status']=false;
        $data['create_time']=time();
        $model=M('Suipai');
        $result = $model->create($data, 1);
        if ($result) {
            //添加数据
            $workid = $model->add($result);
            if ($workid) {
                //更新附件状态
                if ($data['image']) {
                    //更新主图与附件关联表
                    service("Attachment")->api_update('', 'works-' . $workid, 1);
                }
                return $workid;
            } else {
                $this->error = '作品添加失败';
                return false;
            }
        } else {
            return false;
        }
    }


    //随拍作品添加模型
    public function copyAddModel($data){
        if (empty($data)) {
            $this->error = '添加数据不能为空！';
            return false;
        }
        if(mb_strlen($data['title'],'utf-8')<1 || mb_strlen($data['title'],'utf-8')>30){
            $this->error='作品名称不能为空且不能超过30个字符';
            return false;
        }
        if(empty($data['image'])){
            $this->error='请上传作品主图';
            return false;
        }
        if(empty($data['content'])){
            $this->error='请添加作品说明';
            return false;
        }
        $result = $this->create($data, 1);
        if ($result) {
            //添加数据
            $workid = $this->add($result);
            if ($workid) {
                //更新附件状态
                if ($data['image']) {
                    //更新主图与附件关联表
                    service("Attachment")->api_update('', 'works-' . $workid, 1);
                }
                return $workid;
            } else {
                $this->error = '作品添加失败';
                return false;
            }
        } else {
            return false;
        }
    }


    /**
     * 更新参考作品模型
     * @param $post
     * @return bool
     */
    public function copyEditModel($data){
        if(empty($data['workid'])){
            $this->error='获取产品失败';
            return false;
        }
        if(empty($data['image'])){
            $this->error='请上传产品主图';
            return false;
        }
        $workid=$data['workid'];
        $data['status']=false;
        $result = $this->create($data, 2);
        if ($result) {
            //修改数据
            $where['workid']=$workid;
            $status=$this->data($result)->where($where)->save();
            //更新记录,记得如果是TRUE就为===,如果为FLASH则为!==,并不是!=
            if(false!==$status){
                //更新动态状态
               // M('UserDynamic')->where(array('infoid'=>$workid,'userid'=>$data['userid'],'action'=>'workadd'))->setField(array('status'=>false));
                //更新附件状态
                if ($data['image']) {
                    //更新主图与附件关联表
                    service("Attachment")->api_update('', 'works-' . $workid, 1);
                }
                return true;
            } else {
                $this->error = '产品更新失败';
                return false;
            }
        } else {
            return false;
        }
    }


    /**
     * 更新参考作品模型
     * @param $post
     * @return bool
     */
    public function suipaiEditModel($data){
        if(empty($data['id'])){
            $this->error='获取产品失败';
            return false;
        }
        if(empty($data['image'])){
            $this->error='请上传产品主图';
            return false;
        }
        $model=M('Suipai');
        $workid=$data['id'];
        $data['status']=false;
        $result = $model->create($data, 2);
        if ($result) {
            //修改数据
            $where['id']=$workid;
            $status=$model->data($result)->where($where)->save();
            if(false!==$status){
                //更新动态状态
                //M('UserDynamic')->where(array('infoid'=>$workid,'userid'=>$data['userid'],'action'=>'spadd'))->setField(array('status'=>false));
                //更新附件状态
                if ($data['image']) {
                    service("Attachment")->api_update('', 'works-' . $workid, 1);
                }
                return true;
            } else {
                $this->error = '产品更新失败';
                return false;
            }
        } else {
            return false;
        }
    }


    /**
     * 删除作品
     * @param $data
     * @return bool
     */
    public function deleteWorks($data){
        if(empty($data)){
            $this->error='作品删除失败';
            return false;
        }
        $where['workid']=$data;
        $item=$this->field('userid,status')->where($where)->find();
        if($item['status']==true){
            $savearr['worksnum'] = array('exp','worksnum-1');
            $savearr['upoint'] = array('exp','upoint-10');
        }
        $status=$this->relation(true)->where($where)->delete();
        if($status!==false){
            //减去数量与积分操作
            M('User')->where(array('userid'=>$item['userid']))->save($savearr);
            //删除产品主图
            service("Attachment")->api_delete('works-' . $data);
            return true;
        }else{
            return false;
        }
    }

    /**
     * 删除产品
     * @param $data
     * @return bool
     */
    public function deleteSuipai($data){
        if(empty($data)){
            $this->error='作品删除失败';
            return false;
        }
        $where['id']=$data;
        $item=M('Suipai')->field('userid,status')->where($where)->find();
        if($item['status']==true){
            $savearr['spnum'] = array('exp','spnum-1');
            $savearr['upoint'] = array('exp','upoint-3');
        }
        $status=M('Suipai')->where($where)->delete();
        if($status!==false){
            M('User')->where(array('userid'=>$item['userid']))->save($savearr);
            service("Attachment")->api_delete('works-' . $data);
            return true;
        }else{
            return false;
        }
    }


}
